/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * transfer.c
 *
 * Copyright (C) 2008, 2009 Lingtao Pan
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, 
 * Boston, MA 02111-1307, USA.
 */

#include "gftp.h"

static GList* _setup_current_directory_for_transfer (gftp_transfer *transfer, 
                                                     int *ret);

static GHashTable* _gen_dir_hash (gftp_request *request, int *ret);

static int    _lookup_curfle_in_device_hash (gftp_request *request, 
                                             gftp_file    *curfle, 
                                             GHashTable   *device_hash);

static void   _cleanup_get_all_subdirs (gftp_transfer *transfer, 
                                        char *oldfromdir,
                                        char *oldtodir);

static GList* _get_dir_listing (gftp_transfer *transfer,
                                int getothdir, 
                                int *ret);

static void _free_inode_hash   (gpointer key, gpointer value, gpointer user_data);
static void _free_device_hash  (GHashTable *device_hash);
static void _destroy_hash_ent  (gpointer key, gpointer value, gpointer user_data);
static void _destroy_dir_hash  (GHashTable *dirhash);


gftp_transfer *
gftp_transfer_new ()
{
    gftp_transfer * tdata;

    tdata = g_malloc0 (sizeof (*tdata));

    g_static_mutex_init (&tdata->statmutex);
    g_static_mutex_init (&tdata->structmutex);

    return (tdata);
}

/* TODO */
void
gftp_transfer_destroy (gftp_transfer * tdata)
{
    free_file_list (tdata->files);
    if (tdata->thread_id != NULL)
        g_free (tdata->thread_id);
    g_free (tdata);
}


off_t
gftp_transfer_transfer_file (gftp_request *fromreq, 
                             const char   *fromfile, off_t fromsize,        
                             gftp_request *toreq, 
                             const char   *tofile,   off_t tosize)
{
    gdouble maxkbs;
    off_t size;
    int ret;

    g_return_val_if_fail (fromreq != NULL, GFTP_EFATAL);
    g_return_val_if_fail (fromfile != NULL, GFTP_EFATAL);
    g_return_val_if_fail (toreq != NULL, GFTP_EFATAL);
    g_return_val_if_fail (tofile != NULL, GFTP_EFATAL);

    maxkbs = gftp_config_get_double ("General", "maxkbs");

    if (maxkbs > 0) {
        toreq->logging_function (gftp_logging_misc, toreq,
                      _("File transfer will be throttled to %.2f KB/s\n"), 
                      maxkbs);
    }

    if (fromreq->protonum == toreq->protonum &&
        fromreq->transfer_file != NULL)
        return (fromreq->transfer_file (fromreq, fromfile, fromsize, toreq, 
                                        tofile, tosize));

    fromreq->cached = 0;
    toreq->cached = 0;

get_file:
    size = gftp_request_get_file (fromreq, fromfile, tosize);
    if (size < 0)
    {
        if (size == GFTP_ETIMEDOUT)
        {
            ret = gftp_request_connect (fromreq);
            if (ret < 0)
                return (ret);

            goto get_file;
        }

        return (size);
    }

put_file:
    ret = gftp_request_put_file (toreq, tofile, tosize, size);
    if (ret != 0)
    {
        if (size == GFTP_ETIMEDOUT)
        {
            ret = gftp_request_connect (fromreq);
            if (ret < 0)
                return (ret);

            goto put_file;
        }

        if (gftp_request_abort_transfer (fromreq) != 0)
            gftp_request_end_transfer (fromreq);

        return (ret);
    }

    return (size);
}

gboolean
gftp_transfer_is_active (gftp_transfer *transfer)
{
    if (transfer == NULL)
        return FALSE;
  
    if (transfer->started)
        return TRUE;

    return FALSE;
}


int
gftp_transfer_expand_dirs (gftp_transfer * transfer)
{
    GList *iter, *last;
    char *oldfromdir, *oldtodir;
    GHashTable * device_hash;
    gftp_file * curfle;
    off_t linksize;
    mode_t st_mode;
    int ret, isdir;

    g_return_val_if_fail (transfer != NULL, GFTP_EFATAL);
    g_return_val_if_fail (transfer->fromreq != NULL, GFTP_EFATAL);
    g_return_val_if_fail (transfer->files != NULL, GFTP_EFATAL);

    ret = 0;
    last = _setup_current_directory_for_transfer (transfer, &ret);
    if (last == NULL)
        return (ret);

    oldfromdir = oldtodir = NULL;
    device_hash = g_hash_table_new (g_str_hash, g_str_equal);

    for (iter = transfer->files; iter != NULL; iter = iter->next) {
        curfle = iter->data;
    
        if (_lookup_curfle_in_device_hash (transfer->fromreq, curfle,
                                           device_hash))
            continue;

        isdir = S_ISDIR (curfle->st_mode);

        if (S_ISLNK (curfle->st_mode)) {
            st_mode = 0;
            linksize = 0;

            g_assert (!S_ISDIR (curfle->st_mode));
            ret = gftp_request_stat_filename (transfer->fromreq, curfle->file, 
                                              &st_mode, &linksize);      
            if (ret == GFTP_EFATAL) {
                _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
                return (ret);
            } else if (ret == 0) {
                if (S_ISDIR (st_mode))
                    curfle->st_mode = st_mode;
                else
                    curfle->size = linksize;
            }

            /* TODO: rfc959 doesn't have stat_filename(),
             * must use get_file_size() */
            if (linksize == 0) {
                curfle->size = gftp_request_get_file_size (transfer->fromreq, 
                                                           curfle->file);
                if (curfle->size == 0)
                    isdir = 1;
            }
        }

        if (!isdir) {
            transfer->numfiles++;
            continue;
        }

        /* Got a directory... */
        transfer->numdirs++;

        if (oldfromdir == NULL)
            oldfromdir = g_strdup (transfer->fromreq->directory);

        ret = gftp_request_set_directory (transfer->fromreq, curfle->file);
        if (ret < 0) {
            _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
            _free_device_hash (device_hash);
            return (ret);
        }

        if (transfer->toreq != NULL) {
            if (oldtodir == NULL)
                oldtodir = g_strdup (transfer->toreq->directory);

            if (curfle->exists_other_side) {
                ret = gftp_request_set_directory (transfer->toreq, curfle->destfile);
                if (ret == GFTP_EFATAL) {
                    _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
                    _free_device_hash (device_hash);
                    return (ret);
                }
            } else {
                if (transfer->toreq->directory != NULL)
                    g_free (transfer->toreq->directory);
                
                transfer->toreq->directory = g_strdup (curfle->destfile);
            }
        }

        ret = 0;
        last->next = _get_dir_listing (transfer,
                                   curfle->exists_other_side, &ret);
        if (ret < 0) {
            _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
            _free_device_hash (device_hash);
            return (ret);
        }

        if (last->next != NULL) {
            last->next->prev = last;
            for (; last->next != NULL; last = last->next);
        }
    }

    _free_device_hash (device_hash);

    if (oldfromdir != NULL) {
        ret = gftp_request_set_directory (transfer->fromreq, oldfromdir);
        if (ret == GFTP_EFATAL) {
            _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
            return (ret);
        }
    }

    if (oldtodir != NULL) {
        ret = gftp_request_set_directory (transfer->toreq, oldtodir);
        if (ret == GFTP_EFATAL) {
            _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
            return (ret);
        }
    }

    _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);

    return (0);
}


static GHashTable *
_gen_dir_hash (gftp_request * request, int *ret)
{
    GHashTable *dirhash;
    gftp_file *fle;
    off_t *newsize;

    dirhash = g_hash_table_new (g_str_hash, g_str_equal);
    *ret = gftp_request_list_files_begin (request);
    if (*ret == 0) {
        fle = g_malloc0 (sizeof (*fle));
        while (gftp_request_list_files_next (request, NULL, fle) > 0) {
            newsize = g_malloc (sizeof (*newsize));
            *newsize = fle->size;
            g_hash_table_insert (dirhash, fle->file, newsize);
            fle->file = NULL;
            gftp_file_destroy (fle, 0);
        } 

        g_free (fle);
    } else {
        g_hash_table_destroy (dirhash);
        dirhash = NULL;
    }

    gftp_request_end_transfer (request);

    return (dirhash);
}


static GList*
_setup_current_directory_for_transfer (gftp_transfer * transfer, int *ret)
{
    GHashTable * dirhash;
    char *pos, *newname;
    gftp_file * curfle;
    GList * last;
    off_t *newsize;

    *ret = 0;
    if (transfer->toreq != NULL) {
        dirhash = _gen_dir_hash (transfer->toreq, ret);
        if (*ret == GFTP_EFATAL)
            return (NULL);
    } 
    else
        dirhash = NULL;

    for (last = transfer->files; ; last = last->next) {
        curfle = last->data;
    
        if ((pos = strrchr (curfle->file, '/')) != NULL)
            pos++;
        else
            pos = curfle->file;

        if (dirhash != NULL && 
            (newsize = g_hash_table_lookup (dirhash, pos)) != NULL)
        {
            curfle->exists_other_side = 1;
            curfle->startsize = *newsize;
        } 
        else
            curfle->exists_other_side = 0;

    
        if (transfer->toreq && curfle->destfile == NULL)
            curfle->destfile = gftp_build_path (transfer->toreq,
                                                transfer->toreq->directory, 
                                                curfle->file, NULL);

        if (transfer->fromreq->directory != NULL &&
            *transfer->fromreq->directory != '\0' && *curfle->file != '/')
        {
            newname = gftp_build_path (transfer->fromreq,
                                       transfer->fromreq->directory,
                                       curfle->file, NULL);
            g_free (curfle->file);
            curfle->file = newname;
        }

        if (last->next == NULL)
            break;
    }

    _destroy_dir_hash (dirhash);

    return (last);
}

static int
_lookup_curfle_in_device_hash (gftp_request * request, gftp_file * curfle,
                               GHashTable * device_hash)
{
    GHashTable * inode_hash;

    if (curfle->st_dev == 0 || curfle->st_ino == 0)
        return (0);

    if ((inode_hash = g_hash_table_lookup (device_hash,
                                           GUINT_TO_POINTER ((guint) curfle->st_dev))) != NULL)
    {
        if (g_hash_table_lookup (inode_hash,
                                 GUINT_TO_POINTER ((guint) curfle->st_ino)))
        {
            request->logging_function (gftp_logging_error, request,
                                       _("Found recursive symbolic link %s\n"),
                                       curfle->file);
            return (1);
        }

        g_hash_table_insert (inode_hash, GUINT_TO_POINTER ((guint) curfle->st_ino),
                             GUINT_TO_POINTER (1));
        return (0);
    } else {
        inode_hash = g_hash_table_new (uint_hash_function, uint_hash_compare);
        g_hash_table_insert (inode_hash, GUINT_TO_POINTER ((guint) curfle->st_ino),
                             GUINT_TO_POINTER (1));
        g_hash_table_insert (device_hash, GUINT_TO_POINTER ((guint) curfle->st_dev),
                             inode_hash);
        return (0);
    }
}

static void
_cleanup_get_all_subdirs (gftp_transfer * transfer, char *oldfromdir,
                          char *oldtodir)
{
    if (oldfromdir != NULL)
        g_free (oldfromdir);
  
    if (oldtodir != NULL)
        g_free (oldtodir);
}

static GList *
_get_dir_listing (gftp_transfer * transfer, int getothdir, int *ret)
{
    GHashTable * dirhash;
    GList * templist;
    gftp_file * fle;
    off_t *newsize;
    char *newname;

    if (getothdir && transfer->toreq != NULL) {
        dirhash = _gen_dir_hash (transfer->toreq, ret);
        if (*ret == GFTP_EFATAL)
            return (NULL);
    } else 
        dirhash = NULL; 

    *ret = gftp_request_list_files_begin (transfer->fromreq);
    if (*ret < 0) {
        _destroy_dir_hash (dirhash);
        return (NULL);
    }

    fle = g_malloc (sizeof (*fle));
    templist = NULL;
    while (gftp_request_list_files_next (transfer->fromreq, NULL, fle) > 0) {
        if (strcmp (fle->file, ".") == 0 || strcmp (fle->file, "..") == 0) {
            gftp_file_destroy (fle, 0);
            continue;
        }

        if (dirhash && 
            (newsize = g_hash_table_lookup (dirhash, fle->file)) != NULL)
        {
            fle->exists_other_side = 1;
            fle->startsize = *newsize;
        } else
            fle->exists_other_side = 0;

        if (transfer->toreq && fle->destfile == NULL)
            fle->destfile = gftp_build_path (transfer->toreq,
                                             transfer->toreq->directory, 
                                             fle->file, NULL);

        if (transfer->fromreq->directory != NULL &&
            *transfer->fromreq->directory != '\0' &&
            *fle->file != '/')
        {
            newname = gftp_build_path (transfer->fromreq,
                                       transfer->fromreq->directory,
                                       fle->file, NULL);
      
            g_free (fle->file);
            fle->file = newname;
        }

        templist = g_list_append (templist, fle);

        fle = g_malloc0 (sizeof (*fle));
    }

    gftp_request_end_transfer (transfer->fromreq);
    gftp_file_destroy (fle, 1);
    _destroy_dir_hash (dirhash);

    return (templist);
}

static void
_free_inode_hash (gpointer key, gpointer value, gpointer user_data)
{
    g_hash_table_destroy (value);
}


static void
_free_device_hash (GHashTable * device_hash)
{
    g_hash_table_foreach (device_hash, _free_inode_hash, NULL);
    g_hash_table_destroy (device_hash);
}

static void
_destroy_hash_ent (gpointer key, gpointer value, gpointer user_data)
{
    g_free (key);
    g_free (value);
}


static void
_destroy_dir_hash (GHashTable * dirhash)
{
    if (dirhash == NULL)
        return;

    g_hash_table_foreach (dirhash, _destroy_hash_ent, NULL);
    g_hash_table_destroy (dirhash);
}


void     gftp_transfer_merge          (gftp_transfer *transfer, 
                                       gftp_transfer *trans_new)
{
    g_return_if_fail (transfer->fromreq == trans_new->fromreq);
    g_return_if_fail (transfer->toreq == trans_new->toreq);

    transfer->numfiles += trans_new->numfiles;
    transfer->numdirs  += trans_new->numdirs;
    transfer->total_bytes += trans_new->total_bytes;
    transfer->resumed_bytes += trans_new->resumed_bytes;

    transfer->files = g_list_concat (transfer->files, trans_new->files);
    trans_new->files = NULL;
    
    g_free (trans_new);
}

void gftp_transfer_remove_file (gftp_transfer *transfer, gftp_file *fle)
{
    g_return_if_fail (fle != NULL);

    if (transfer->curfle->data == (gpointer)fle) {
        transfer->curfle = transfer->curfle->next;
    }

    transfer->files = g_list_remove (transfer->files, (gpointer)fle);
}


void gftp_transfer_exchange_file_pos (gftp_transfer *transfer, 
                         gftp_file *fle1, gftp_file *fle2)
{
    GList *l1, *l2;
    
    l1 = g_list_find (transfer->files, (gpointer)fle1);
    l2 = g_list_find (transfer->files, (gpointer)fle2);
    
    g_assert (l1 != NULL);
    g_assert (l2 != NULL);
    g_assert (l1 != l2);

    l1->data = (gpointer) fle2;
    l2->data = (gpointer) fle1;
}


int
gftp_get_all_subdirs (gftp_transfer * transfer)
{
    GList * templist, * lastlist;
    char *oldfromdir, *oldtodir;
    GHashTable * device_hash;
    gftp_file * curfle;
    off_t linksize;
    mode_t st_mode;
    int ret;

    g_return_val_if_fail (transfer != NULL, GFTP_EFATAL);
    g_return_val_if_fail (transfer->fromreq != NULL, GFTP_EFATAL);
    g_return_val_if_fail (transfer->files != NULL, GFTP_EFATAL);

    if (transfer->files == NULL)
        return (0);

    ret = 0;
    lastlist = _setup_current_directory_for_transfer (transfer, &ret);
    if (lastlist == NULL)
        return (ret);

    oldfromdir = oldtodir = NULL;
    device_hash = g_hash_table_new (uint_hash_function, uint_hash_compare);

    for (templist = transfer->files; templist != NULL; 
         templist = templist->next)
    {
        curfle = templist->data;

        if (_lookup_curfle_in_device_hash (transfer->fromreq, curfle,
                                           device_hash))
            continue;

        if (S_ISLNK (curfle->st_mode) && !S_ISDIR (curfle->st_mode)) {
            st_mode = 0;
            linksize = 0;
            ret = gftp_request_stat_filename (transfer->fromreq, curfle->file, 
                                              &st_mode, &linksize);
            if (ret == GFTP_EFATAL) {
                _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
                return (ret);
            } else if (ret == 0) {
                if (S_ISDIR (st_mode))
                    curfle->st_mode = st_mode;
                else
                    curfle->size = linksize;
            }
        }

        if (!S_ISDIR (curfle->st_mode)) {
            transfer->numfiles++;
            continue;
        }

        /* Got a directory... */
        transfer->numdirs++;

        if (oldfromdir == NULL)
            oldfromdir = g_strdup (transfer->fromreq->directory);

        ret = gftp_request_set_directory (transfer->fromreq, curfle->file);
        if (ret < 0) {
            _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
            _free_device_hash (device_hash);
            return (ret);
        }

        if (transfer->toreq != NULL) {
            if (oldtodir == NULL)
                oldtodir = g_strdup (transfer->toreq->directory);

            if (curfle->exists_other_side) {
                ret = gftp_request_set_directory (transfer->toreq, 
                                                  curfle->destfile);
                if (ret == GFTP_EFATAL) {
                    _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
                    _free_device_hash (device_hash);
                    return (ret);
                }
            } else {
                if (transfer->toreq->directory != NULL)
                    g_free (transfer->toreq->directory);

                transfer->toreq->directory = g_strdup (curfle->destfile);
            }
        }

        ret = 0;
        lastlist->next = _get_dir_listing (transfer,
                                           curfle->exists_other_side, &ret);
        if (ret < 0) {
            _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
            _free_device_hash (device_hash);
            return (ret);
        }

        if (lastlist->next != NULL) {
            lastlist->next->prev = lastlist;
            for (; lastlist->next != NULL; lastlist = lastlist->next);
        }
    }

    _free_device_hash (device_hash);

    if (oldfromdir != NULL)
    {
        ret = gftp_request_set_directory (transfer->fromreq, oldfromdir);
        if (ret == GFTP_EFATAL)
        {
          _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
          return (ret);
        }
    }

    if (oldtodir != NULL)
    {
        ret = gftp_request_set_directory (transfer->toreq, oldtodir);
        if (ret == GFTP_EFATAL)
        {
            _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);
            return (ret);
        }
    }

    _cleanup_get_all_subdirs (transfer, oldfromdir, oldtodir);

    return (0);
}
